package com.itcast.cn;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * post和get通用获取参数的方式
 */
@WebServlet("/demo4")
public class ServletDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("get");
        dealALL(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    private void dealALL(HttpServletRequest request, HttpServletResponse response) {
        //针对Post请求中中文乱码的问题
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //公共方法
        //获取所有键值对map
        Map<String, String[]> map = request.getParameterMap();
        for (String key : map.keySet()) {
            System.out.print(key +":");
            String[] values = map.get(key);
            for (String value : values) {
                System.out.print(value);
            }
            System.out.println();
            System.out.println("------------");
        }


        //针对
        String[] hobbies = request.getParameterValues("hobby");
        String haha = "";
        for (String hobby : hobbies) {
            haha += hobby+"  ";
        }
        System.out.println("获取的兴趣爱好是："+haha);

        //https://www.cnblogs.com/wpcnblog/p/12358143.html
        String username = request.getParameter("name");
        System.out.println("获取的姓名是："+username);
        System.out.println("AAAA"+username);
        //GET，获取参数的方式：getQueryString()
        //乱码原因：Tomcat进行URL解码。默认的字符集ISO-8853-1
        //1。先对乱码数据进行编码，转为字节数组
        byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);
        //2,字节数组解码
        String s = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("BBB："+s);

        String password = request.getParameter("password");
        System.out.println("获取的密码是："+password);

    }

}
